<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\agent\controller;

use controller\BasicAgent;
use service\DataService;
use think\Db;

/**
 * 微信粉丝管理
 * Class Fans
 * @package app\wechat\controller
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/03/27 14:43
 */
class Member extends BasicAgent
{

    /**
     * 定义当前默认数据表
     * @var string
     */
    public $table = 'store_member';

    /**
     * 显示粉丝列表
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function index()
    {
        $this->title = '用户中心';
        $get = $this->request->get();
        $db = Db::name($this->table);
        if (isset($get['shop_id']) && $get['shop_id'] != '') {
            $where['shop_id'] = $get['shop_id'];
            $db->where($where);
        }
        if(isset($get['member_level']) && $get['member_level'] !== ''){
            $where['member_level'] = $get['member_level'];
            $db->where($where);
        }

        if (isset($get['create_at']) && $get['create_at'] != ''){
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $num = Db::name('store_member');
            $num->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
            $count['time'] = 2;
            $usrnum1 = [
                'shop_id' => $get['shop_id'],
                'member_level' => 1
            ];
            $usrnum2 = [
                'shop_id' => $get['shop_id'],
                'member_level' => 2
            ];
            $count['vip'] = $num->where($usrnum2)->count();
            $count['yubei'] = $num->where($usrnum1)->count();
        }else{
            $count['time'] = 3;
            $usrnum1 = [
                'shop_id' => $get['shop_id'],
                'member_level' => 1
            ];
            $usrnum2 = [
                'shop_id' => $get['shop_id'],
                'member_level' => 2
            ];
            $count['vip'] = Db::name('store_member')->where($usrnum2)->count();
            $count['yubei'] = Db::name('store_member')->where($usrnum1)->count();
        }
        $this->assign('count',$count);


        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        foreach (['phone', 'member_level'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db->order('id desc'));
    }

    public function _index_data_filter( &$data )
    {
        foreach($data as &$v) {
            $v['member_level_info'] = Db::name('sys_level')->where(['id' => $v['member_level']])->value('title');
            $v['team_num'] = Db::query("SELECT count(*) as sub_person_count  FROM `store_member` WHERE FIND_IN_SET({$v['id']},all_leader)")[0]['sub_person_count'];
            $v['company'] = Db::name('store_shops')->where(['id'=>$v['shop_id']])->find();
        }
        $sys_level = Db::name('sys_level')->select();
        $this->assign('sys_level',$sys_level);
    }
    /**
     * 列表数据处理
     * @param array $list
     */
    public function add()
    {
        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        return $this->_form($this->table, 'form');
    }

    public function carid(){
        $this->title = "历史车牌";
        $get = input('get.');
        $db = Db::name('store_member_carid')
            ->alias('a')
            ->join('store_member b','a.uid = b.id')
            ->field('b.truename,a.id,a.sheng,a.carid,a.addtime');
        if (isset($get['id']) && $get['id'] !== '' ){
            $where['uid'] = $get['id'];
            $db->where($where);
        }

        return parent::_list($db->order('id desc'));
    }


    
    public function edit()
    {
        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        return $this->_form($this->table, 'form');
    }

    /**
     * 用户禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        if (DataService::update($this->table)) {
            $this->success("用户禁用成功！", '');
        }
        $this->error("用户禁用失败，请稍候再试！");
    }

    /**
     * 用户禁用
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        if (DataService::update($this->table)) {
            $this->success("用户启用成功！", '');
        }
        $this->error("用户启用失败，请稍候再试！");
    }

  

    public function getTreeMember($member_id =0){
        $list = [];
        $users =    Db::name('store_member a')
            ->field('a.id,a.nickname,a.create_at,a.phone,a.account_money,b.title,a.create_at')
            ->join('sys_level b',"a.member_level = b.id")
            ->where(['a.first_leader'=>$member_id])->select();
        if (!empty($users) && check_arr($users)) {
            foreach ($users as $k => &$v) {
                $v['children'] = $this->getTreeMember($v['id']);
                $list[] = $v;
            }
        }
        return $list;
    }

    //身份认证审核
    public function idaudit()
    {
        $this->title = '身份认证管理';
        $get = $this->request->get();
        $db = Db::name("store_member_idcard");
        $where = array();
        if (isset($get['type']) && $get['type'] != '') {
            $where['status'] = $get['type'];
            $db->where($where);
        }
//        sm($get);
        if (isset($get['name']) && $get['name'] != '') {
            $where['uid'] = Db::name('store_member')->where(array('phone' => $get['name']))->value('id');
            $db->where($where);
        }
        $db->order('id desc');
       return parent::_list($db);
    }

    
    //身份认证操作

    public function idpass()
    {
        $param = input('param.');
        Db::startTrans();
        if($param['status'] == 1){
            $db[] = Db::name('store_member_idcard')->where(['id'=>$param['id']])->update(['status'=>$param['status']]);
            $db[] = mlog($param['uid'],'mining',sysconf('sharenoting'),'实名认证通过赠送分享算力'.sysconf('sharenoting').'个');
            $userInfo = Db::name('store_member')->where(['id'=>$param['uid']])->find();
            if($userInfo['first_leader'] > 0){
                $content = "推广{$userInfo['nickname']},获取到分享算力:10";
                $db[] = mlog($userInfo['first_leader'], 'mining', 10, $content, 'share_dig_spread');
            }
        }elseif($param['status'] == 2){
            $db[] = Db::name('store_member_idcard')->where(['id'=>$param['id']])->update(['status'=>$param['status']]);
        }

        if (check_arr($db)){
            Db::commit();
            $this->success('操作成功');
        } else{
            Db::rollback();
            $this->error('操作失败');
        }
    }
    
    
    
    /**
     * 分销树状关系
     */
    public function member_org()
    {
        set_time_limit(0);
        $users = Db::name('store_member');
        $id = $_GET['member_id'];
        $list = Db::name('store_member')->where([
            'first_leader' => $id
        ])->select();

        foreach ($list as $key => $v) {
            $list[$key]['share'] = get_share_num($v['id']);
            //$list[$key]['team_share'] = get_team_share_num($v['id']);
            //   $list[$key]['children'] = self::handleUser($v['id'], $layer);

        }

        // 伞下会员用户id
      //  $umbrella_member_ids = Db::name('store_member')->where('leaders', 'like', "%$id%")->column('id');



        return view('', [
            'id' => $id,
            'list' => $list,

        ]);
    }

    /**
     * 获取某个人下级元素
     */
    public function ajax_lower()
    {
        $id = $_GET['id'];
        $list = Db::name('store_member')->where([
            'first_leader' => $id
        ])->select();
        foreach ($list as $key => $v) {
            $list[$key]['share'] = get_share_num($v['id']);

        }

        return view('', [
            'list' => $list
        ]);
    }


    public function shops()
    {
        $this->title = '商家列表';
        $get = $this->request->get();

        $db = Db::table('store_shops');

        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }

        if (isset($get['nickname']) && $get['nickname'] !== '') {
            $db->where('name', 'like',"%{$get['nickname']}%");
        }
        if (isset($get['shop_name']) && $get['shop_name'] !== '') {
            $db->where('shop_name', 'like',"%{$get['shop_name']}%");
        }
        if (isset($get['phone']) && $get['phone'] !== '') {
            $db->where('phone', 'like',"%{$get['phone']}%");
        }
        if (isset($get['member_level']) && $get['member_level'] !== '') {
            $db->where('member_level', '=',$get['member_level']);
        }

       // dump($this->user['username']);
        $db->where('admininfo', $this->user['username']);

       // dump($db);
        return parent::_list($db->order('create_at desc'));
    }

    public function shopadd()
    {
        if(request()->isPost()){
            $post = request()->post();

            $shop = Db::name('store_shops')->order('id desc')->find();
            $exsit = Db::name('sys_lettery')->where("shop_id",$shop['id'])->find();
            if (!$exsit) {
                $insertdata1 = [
                    'title' => '一级功勋',
                    'create_at' => date("Y-m-d H:i:s", time()),
                    'sort' => 1,
                    'shuliang' => 5,
                    'shop_id' => $shop['id']
                ];
                $insertdata2 = [
                    'title' => '二级功勋',
                    'create_at' => date("Y-m-d H:i:s", time()),
                    'sort' => 2,
                    'shuliang' => 10,
                    'shop_id' => $shop['id']
                ];
                $insertdata3 = [
                    'title' => '三级功勋',
                    'create_at' => date("Y-m-d H:i:s", time()),
                    'sort' => 3,
                    'shuliang' => 15,
                    'shop_id' => $shop['id']
                ];
                $insertdata4 = [
                    'title' => '四级功勋',
                    'create_at' => date("Y-m-d H:i:s", time()),
                    'sort' => 4,
                    'shuliang' => 20,
                    'shop_id' => $shop['id']
                ];
                Db::name("sys_lettery")->insert($insertdata1);
                Db::name("sys_lettery")->insert($insertdata2);
                Db::name("sys_lettery")->insert($insertdata3);
                Db::name("sys_lettery")->insert($insertdata4);
            }

        }
        $areaList = Db::name('sys_address')->where(['area_parent_id'=>0])->select();
        $this->assign('areaList', $areaList);
        $this->assign('admininfo', $this->user['username']);
        return $this->_form('store_shops', 'shop_add');
    }
    public function shopedit()
    {
        if(request()->isPost()){
            $post = request()->post();
            if($post['admininfo']!='')
            {
                if(!Db::name('agent')->where('username',$post['admininfo'])->find())
                {
                    $this->error('您输入的代理不存在!');
                }
            }


        }
        $areaList = Db::name('sys_address')->where(['area_parent_id'=>0])->select();
        $areaifno = Db::name('sys_address')->where('area_parent_id','>',0)->select();
        $type = 'edit';
        $this->assign('type',$type);
        $this->assign('areaList', $areaList);
        $this->assign('areaifno', $areaifno);
        $this->assign('admininfo', $this->user['username']);
        return $this->_form('store_shops', 'shop_add');
    }


    public function pass(){
        if ($this->request->isGet()) {
            $this->assign('verify', false);
            $this->table = 'store_shops';
            return $this->_form($this->table, 'pass');
        }
        $post = $this->request->post();
        if ($post['password'] !== $post['repassword']) {
            $this->error('两次输入的密码不一致！');
        }
        $data = ['id' => $post['id'], 'password' => $post['password']];
        if (DataService::save($this->table, $data, 'id')) {
            $this->success('密码修改成功，下次请使用新密码登录！', '');
        }
        $this->error('密码修改失败，请稍候再试！');
    }

    //下级用户
    public function lower(){
        $this->title = '用户中心';
        $get = $this->request->get();
        $db = Db::name('store_member');
        if (isset($get['id']) && $get['id'] != '') {
            $where['first_leader'] = $get['id'];
            $db->where($where);
        }


        $levellist = Db::name('sys_level')->select();
        $this->assign('level',$levellist);
        foreach (['phone', 'member_level'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db->order('id desc'));
    }




    public function shopbalance()
    {
        if($this->request->post()){
            $data = $this->request->post();
            if($data['member_id']){
                $content_str = '';
                if($data['recharge_type'] ==1){
                    $content_str = "后台减少用户:{$data['member_id']},金额:{$data['account_money']}";
                    $data['account_money'] = '-'.$data['account_money'];
                }else{
                    $content_str = "后台增加用户:{$data['member_id']},金额:{$data['account_money']}";
                    $data['account_money'] = $data['account_money'];
                }
                Db::startTrans();
                $res = shopmlog($data['member_id'],'account_money',$data['account_money'],$content_str,'20');
                if(check_arr($res)){
                    Db::commit();
                    return $this->success('操作成功');
                }else{
                    Db::rollback();
                    return $this->error('操作失败');
                }
            }else{
                return $this->error('账户不存在！');
            }
        }
        return view();
    }


    public function cityList()
    {
        $info = $this->request->post();
        if(!empty($info['provinceid'])){
            $goodsInfo=Db::name('sys_address')->where(['area_parent_id'=>$info['provinceid']])->select();
            return $this->result($goodsInfo,200,'成功','');
        }
        return $this->renderError('缺少参数');
    }

    public  function districtList(){
        $info = $this->request->post();
        if(!empty($info['cityid'])){
            $goodsInfo=Db::name('sys_address')->where(['area_parent_id'=>$info['cityid']])->select();
            return $this->result($goodsInfo,200,'成功','');
        }
        return $this->renderError('缺少参数');
    }

    /**
     * 设置黑名单
     */
    public function backadd()
    {
        $this->error("您没有权限更改用户积分");
        /*try {
            $is_disable = Db::name('store_shops')->where('id', input('param.id'))->value('is_disable');
            $is_disable = $is_disable == 1 ? -1 : 1;
            Db::name('store_shops')->where('id', input('param.id'))->setField('is_disable', $is_disable);
        } catch (\Exception $e) {
            $this->error("操作失败，请稍候再试！");
        }
        $this->success('操作成功！', '');*/
    }

}
